package com.example.xd.tuiliu_test.rtmp;

import android.content.res.Configuration;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.example.xd.tuiliu_test.R;
import com.github.faucamp.simplertmp.RtmpHandler;
import com.seu.magicfilter.utils.MagicFilterType;

import net.ossrs.yasea.SrsCameraView;
import net.ossrs.yasea.SrsEncodeHandler;
import net.ossrs.yasea.SrsPublisher;
import net.ossrs.yasea.SrsRecordHandler;

import java.io.IOException;
import java.net.SocketException;

public class PushStreamActivity extends AppCompatActivity implements SrsEncodeHandler.SrsEncodeListener,
        SrsRecordHandler.SrsRecordListener,
        RtmpHandler.RtmpListener, View.OnClickListener {


    public static String TAG = "PushStreamActivity---";
    private SrsCameraView mGlsurfaceview_camera;
    public static String rtmpUrl = "rtmp://10.1.120.224/tuiliu_test/test";
    private SrsPublisher mSrsPublisher;

    private int mWidth = 1920;
    private int mHeight = 1080;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_push_stream);
        findViewById(R.id.btn_change).setOnClickListener(this);
        Log.i("xd-----------", mWidth + "----" + mHeight);
        mGlsurfaceview_camera = findViewById(R.id.glsurfaceview_camera);
        mGlsurfaceview_camera.setCameraId(Camera.CameraInfo.CAMERA_FACING_BACK);//0是后置,1是前置
//        mGlsurfaceview_camera.setCameraId(Camera.CameraInfo.CAMERA_FACING_FRONT);//0是后置,1是前置
        mSrsPublisher = new SrsPublisher(mGlsurfaceview_camera);
        //编码状态回调
        mSrsPublisher.setEncodeHandler(new SrsEncodeHandler(this));
        //rtmp推流状态回调
        mSrsPublisher.setRtmpHandler(new RtmpHandler(this));
        mSrsPublisher.setRecordHandler(new SrsRecordHandler(this));

        //预览分辨率
        mSrsPublisher.setPreviewResolution(mWidth, mHeight);
        //推流分辨率
        mSrsPublisher.setOutputResolution(mHeight, mWidth);
        //传输率
        mSrsPublisher.setVideoHDMode();
        //开启美颜（其他滤镜效果在MagicFilterType中查看）
        mSrsPublisher.switchCameraFilter(MagicFilterType.BEAUTY);
        //打开摄像头，开始预览（未推流）
        mSrsPublisher.startCamera();
//        mSrsPublisher.switchToSoftEncoder();//选择软编码
        mSrsPublisher.switchToHardEncoder();//选择硬编码
        //开始推流 rtmpUrl（ip换成服务器的部署ip）："rtmp://192.168.31.126/android/teststream"
        mSrsPublisher.startPublish(rtmpUrl);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mSrsPublisher.getCamera() == null) {
            mSrsPublisher.startCamera();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mSrsPublisher.resumeRecord();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mSrsPublisher.pauseEncode();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mSrsPublisher.stopPublish();
        mSrsPublisher.stopRecord();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mSrsPublisher.stopEncode();
        mSrsPublisher.stopRecord();
        mSrsPublisher.setScreenOrientation(newConfig.orientation);
        mSrsPublisher.startCamera();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_id1:
                mSrsPublisher.switchCameraFilter(MagicFilterType.FAIRYTALE);
                return true;
            case R.id.menu_id2:
                mSrsPublisher.switchCameraFilter(MagicFilterType.SUNRISE);
                return true;
            case R.id.menu_id3:
                mSrsPublisher.switchCameraFilter(MagicFilterType.SUNSET);
                return true;
            case R.id.menu_id4:
                mSrsPublisher.switchCameraFilter(MagicFilterType.WHITECAT);
                return true;
            case R.id.menu_id5:
                mSrsPublisher.switchCameraFilter(MagicFilterType.BLACKCAT);
                return true;
            case R.id.menu_id6:
                mSrsPublisher.switchCameraFilter(MagicFilterType.SKINWHITEN);
                return true;
            case R.id.menu_id7:
                mSrsPublisher.switchCameraFilter(MagicFilterType.BEAUTY);
                return true;
            case R.id.menu_id8:
                mSrsPublisher.switchCameraFilter(MagicFilterType.HEALTHY);
                return true;
            case R.id.menu_id9:
                mSrsPublisher.switchCameraFilter(MagicFilterType.SWEETS);
                return true;
            case R.id.menu_id10:
                mSrsPublisher.switchCameraFilter(MagicFilterType.ROMANCE);
                return true;
            case R.id.menu_id11:
                mSrsPublisher.switchCameraFilter(MagicFilterType.SAKURA);
                return true;
            case R.id.menu_id12:
                mSrsPublisher.switchCameraFilter(MagicFilterType.WARM);
                return true;
            case R.id.menu_id13:
                mSrsPublisher.switchCameraFilter(MagicFilterType.ANTIQUE);
                return true;
            case R.id.menu_id14:
                mSrsPublisher.switchCameraFilter(MagicFilterType.NOSTALGIA);
                return true;
            case R.id.menu_id15:
                mSrsPublisher.switchCameraFilter(MagicFilterType.CALM);
                return true;
            case R.id.menu_id16:
                mSrsPublisher.switchCameraFilter(MagicFilterType.LATTE);
                return true;
            case R.id.menu_id17:
                mSrsPublisher.switchCameraFilter(MagicFilterType.TENDER);
                return true;
            case R.id.menu_id18:
                mSrsPublisher.switchCameraFilter(MagicFilterType.COOL);
                return true;
            case R.id.menu_id19:
                mSrsPublisher.switchCameraFilter(MagicFilterType.EMERALD);
                return true;
            case R.id.menu_id20:
                mSrsPublisher.switchCameraFilter(MagicFilterType.EVERGREEN);
                return true;
            default:
                mSrsPublisher.switchCameraFilter(MagicFilterType.NONE);
                return true;
        }

    }

    private void handleException(Exception e) {
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        try {
            Log.i(TAG, e.getMessage());
            mSrsPublisher.stopPublish();
            mSrsPublisher.stopRecord();
        } catch (Exception e1) {
        }
    }

    //----------------SrsEncodeHandler-----------------------------------
    @Override
    public void onNetworkWeak() {
        Log.i(TAG, "onNetworkWeak");
    }

    @Override
    public void onNetworkResume() {
        Log.i(TAG, "onNetworkResume");

    }

    @Override
    public void onEncodeIllegalArgumentException(IllegalArgumentException e) {
        Log.i(TAG, "onEncodeIllegalArgumentException");
        handleException(e);
    }

    //---------------------SrsRecordHandler-------------------------------
    @Override
    public void onRecordPause() {
        Log.i(TAG, "onRecordPause");

    }

    @Override
    public void onRecordResume() {
        Log.i(TAG, "onRecordResume");

    }

    @Override
    public void onRecordStarted(String msg) {
        Log.i(TAG, "v");

    }

    @Override
    public void onRecordFinished(String msg) {
        Log.i(TAG, "onRecordFinished");

    }

    @Override
    public void onRecordIllegalArgumentException(IllegalArgumentException e) {
        Log.i(TAG, "onRecordIllegalArgumentException");
        handleException(e);

    }

    @Override
    public void onRecordIOException(IOException e) {
        Log.i(TAG, "onRecordIOException");
        handleException(e);

    }

    //-------------RtmpHandler------------------------------------
    @Override
    public void onRtmpConnecting(String msg) {
        Log.i(TAG, "onRtmpConnecting----" + msg);

    }

    @Override
    public void onRtmpConnected(String msg) {
        Log.i(TAG, "onRtmpConnected----" + msg);

    }

    @Override
    public void onRtmpVideoStreaming() {
        Log.i(TAG, "onRtmpVideoStreaming");

    }

    @Override
    public void onRtmpAudioStreaming() {
        Log.i(TAG, "onRtmpAudioStreaming");

    }

    @Override
    public void onRtmpStopped() {
        Log.i(TAG, "onRtmpStopped");

    }

    @Override
    public void onRtmpDisconnected() {
        Log.i(TAG, "onRtmpDisconnected");

    }

    @Override
    public void onRtmpVideoFpsChanged(double fps) {
        Log.i(TAG, "onRtmpVideoFpsChanged");

    }

    @Override
    public void onRtmpVideoBitrateChanged(double bitrate) {
        Log.i(TAG, "onRtmpVideoBitrateChanged");
        int rate = (int) bitrate;
        if (rate / 1000 > 0) {
            Log.i(TAG, String.format("Audio bitrate: %f kbps", bitrate / 1000));
        } else {
            Log.i(TAG, String.format("Audio bitrate: %d bps", rate));
        }

    }

    @Override
    public void onRtmpAudioBitrateChanged(double bitrate) {
        Log.i(TAG, "onRtmpAudioBitrateChanged");
        int rate = (int) bitrate;
        if (rate / 1000 > 0) {
            Log.i(TAG, String.format("Video bitrate: %f kbps", bitrate / 1000));
        } else {
            Log.i(TAG, String.format("Video bitrate: %d bps", rate));
        }

    }

    @Override
    public void onRtmpSocketException(SocketException e) {
        Log.i(TAG, "onRtmpSocketException");
        handleException(e);
    }

    @Override
    public void onRtmpIOException(IOException e) {
        Log.i(TAG, "onRtmpIOException");
        handleException(e);

    }

    @Override
    public void onRtmpIllegalArgumentException(IllegalArgumentException e) {
        Log.i(TAG, "onRtmpIllegalArgumentException");
        handleException(e);

    }

    @Override
    public void onRtmpIllegalStateException(IllegalStateException e) {
        Log.i(TAG, "onRtmpIllegalStateException");
        handleException(e);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_change:
                if (mSrsPublisher.getCameraId() == Camera.CameraInfo.CAMERA_FACING_BACK) {
                    Log.i("xd-------", "前");
                    mSrsPublisher.switchCameraFace(Camera.CameraInfo.CAMERA_FACING_FRONT);
                } else {
                    Log.i("xd-------", "后");
                    mSrsPublisher.switchCameraFace(Camera.CameraInfo.CAMERA_FACING_BACK);
                }
                break;
        }
    }
}
